package com.tdu.spider.biz.service.weidian;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.mongodb.client.model.WriteModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinService {

	private static final Logger LOGGER = LoggerFactory.getLogger(WeixinService.class);
	public static final String AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	public static final String token = "_EwWqqVIQNvUFWyR_AVJeFbV4K8NAxEPorb0oxTAA6S9wSEYjkRrR-cbtuVII486B5EOviyYOcOaavUlG59nb_TkQvUv59Tg5O9ppKDz-NvthJ7JmFHQ612dCL2oyrWIhJfQL3syV4M9RkjfKuIFbvzCl-0FDvmCdBZ83L6yQQq6wtaFVTwk";
	private String content = "{\"token\":\"_EwWqqVIQNvUFWyR_AVJeFbV4K8NAxEPorb0oxTAA6S9wSEYjkRrR-cbtuVII486B5EOviyYOcOaavUlG59nb_TkQvUv59Tg5O9ppKDz-NvthJ7JmFHQ612dCL2oyrWIhJfQL3syV4M9RkjfKuIFbvzCl-0FDvmCdBZ83L6yQQq6wtaFVTwk\",\"userID\":\"336429028\",\"appid\":\"wxbuyer\",\"wduserID\":\"336429028\",\"anonymousId\":\"077838310695\",\"wxappid\":\"wx4b74228baa15489a\"}";

	public static void main(String[] args) {
		new WeixinService().run("化妆品");
	}

	public void run(String keyword) {
		ItemPageQuery itemPageQuery = new ItemPageQuery();
		itemPageQuery.setLimit(100);
		itemPageQuery.setKeyWord(keyword);
		List<PageItemResult.ResultBean.ViewDatasBean> viewDatasBeans = queryPageItemList(itemPageQuery);
		List<List<Object>> list = Lists.newArrayList();

		for (int i = 0; i < 1; i++) {
			for (PageItemResult.ResultBean.ViewDatasBean viewDatasBean : viewDatasBeans) {
				try {
					TimeUnit.MILLISECONDS.sleep(200L);
				} catch (InterruptedException e) {
				}

				ItemResult.ResultBean.ItemInfoBean itemInfoBean = queryItemDetail(viewDatasBean.getSearchSingleItemDO().getItem().getItemId());
				if (itemInfoBean == null) {
					LOGGER.error("Error");
					continue;
				}
				ItemResult.ResultBean.ItemInfoBean.ItemAssistantInfoBean itemAssistantInfo = itemInfoBean.getItemAssistantInfo();
				int commentCount = 0;
				String favorRate = "0.00%";
				if (itemAssistantInfo != null) {
					if (itemAssistantInfo.getItemDetailComment() != null) {
						commentCount = itemAssistantInfo.getItemDetailComment().getCommentCount();
						favorRate = itemAssistantInfo.getItemDetailComment().getFavorRate();
					}
				}

				ItemDetailVO itemDetailVO = new ItemDetailVO();
				itemDetailVO.setShopName(viewDatasBean.getSearchSingleItemDO().getShopName());
				itemDetailVO.setShopScore(viewDatasBean.getSearchSingleItemDO().getShopScore());
				itemDetailVO.setRepurRatePercent(viewDatasBean.getSearchSingleItemDO().getRepurRatePercent());
				itemDetailVO.setPayedTotal(viewDatasBean.getSearchSingleItemDO().getPayedTotal());
				itemDetailVO.setShopUrl("https://weidian.com/?userid=" + viewDatasBean.getSearchSingleItemDO().getShopId() + "&spider_token=99fa");
				itemDetailVO.setItemName(itemInfoBean.getBaseItemInfo().getItemName());
				itemDetailVO.setItemPrice(Double.valueOf(itemInfoBean.getBaseItemInfo().getItemPrice() / 100));
				itemDetailVO.setCommentCount(commentCount);
				itemDetailVO.setFavorRate(favorRate);
				itemDetailVO.setItemSoldout(itemInfoBean.getBaseItemInfo().getItemSoldout());
				itemDetailVO.setFavoriteCount(itemInfoBean.getBaseItemInfo().getFavoriteCount());
				itemDetailVO.setItemStock(itemInfoBean.getBaseItemInfo().getItemStock());
				itemDetailVO.setFreeDelivery(itemInfoBean.getBaseItemInfo().getFreeDelivery() == 1 ? "是" : "否");
				List<Object> item = Lists.newArrayList();
				item.add(itemDetailVO.getShopName());
				item.add(itemDetailVO.getShopScore());
				item.add(itemDetailVO.getRepurRatePercent());
				item.add(itemDetailVO.getPayedTotal());
				item.add(itemDetailVO.getShopUrl());
				item.add(itemDetailVO.getItemName());
				item.add(itemDetailVO.getItemPrice());

				item.add(commentCount);
				item.add(favorRate);
				item.add(itemDetailVO.getFavoriteCount());
				item.add(itemDetailVO.getItemSoldout());
				item.add(itemDetailVO.getItemStock());
				item.add(itemDetailVO.getFreeDelivery());
				list.add(item);

				LOGGER.info("商铺名称:{},商铺评分:{},商铺复购率:{},商铺关注人数:{},商铺链接:{},商品名称:{},商品价格:{},商品评价数:{},商品好评率:{},商品收藏:{},商品销量:{},商品库存:{},商品运费:{}", itemDetailVO.getShopName(), itemDetailVO.getShopScore(),
						itemDetailVO.getRepurRatePercent(), itemDetailVO.getPayedTotal(), itemDetailVO.getShopUrl(), itemDetailVO.getItemName(), itemDetailVO.getItemPrice(), commentCount, favorRate,
						itemDetailVO.getFavoriteCount(), itemDetailVO.getItemSoldout(), itemDetailVO.getItemStock(), itemDetailVO.getFreeDelivery());
			}
		}

		writeExcel(list);
	}

	public void writeExcel(List<List<Object>> list) {
		try {
			OutputStream out = new FileOutputStream("C:\\Users\\lubinsu\\Desktop\\1.xlsx");
			ExcelWriter writer = EasyExcelFactory.getWriter(out);
			//写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
			Sheet sheet1 = new Sheet(1, 3);
			sheet1.setSheetName("data");

			List<List<String>> head = new ArrayList<List<String>>();
			List<String> headCoulumn1 = new ArrayList<String>();
			List<String> headCoulumn2 = new ArrayList<String>();
			List<String> headCoulumn3 = new ArrayList<String>();
			List<String> headCoulumn4 = new ArrayList<String>();
			List<String> headCoulumn5 = new ArrayList<String>();
			List<String> headCoulumn6 = new ArrayList<String>();
			List<String> headCoulumn7 = new ArrayList<String>();
			List<String> headCoulumn8 = new ArrayList<String>();
			List<String> headCoulumn9 = new ArrayList<String>();

			List<String> headCoulumn10 = new ArrayList<String>();
			List<String> headCoulumn11 = new ArrayList<String>();
			List<String> headCoulumn12 = new ArrayList<String>();
			List<String> headCoulumn13 = new ArrayList<String>();

			headCoulumn1.add("商铺名称");
			headCoulumn2.add("商铺评分");
			headCoulumn3.add("商铺复购率");
			headCoulumn4.add("商铺关注人数");
			headCoulumn5.add("商铺链接");
			headCoulumn6.add("商品名称");
			headCoulumn7.add("商品价格");
			headCoulumn8.add("商品评价数");
			headCoulumn9.add("商品好评率");
			headCoulumn10.add("商品收藏");
			headCoulumn11.add("商品销量");
			headCoulumn12.add("商品库存");
			headCoulumn13.add("商品含运费");

			head.add(headCoulumn1);
			head.add(headCoulumn2);
			head.add(headCoulumn3);
			head.add(headCoulumn4);
			head.add(headCoulumn5);
			head.add(headCoulumn6);
			head.add(headCoulumn7);
			head.add(headCoulumn8);
			head.add(headCoulumn9);
			head.add(headCoulumn10);
			head.add(headCoulumn11);
			head.add(headCoulumn12);
			head.add(headCoulumn13);

			sheet1.setHead(head);
			//or 设置自适应宽度
			sheet1.setAutoWidth(Boolean.TRUE);
			writer.write1(list, sheet1);
			writer.finish();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<PageItemResult.ResultBean.ViewDatasBean> queryPageItemList(ItemPageQuery itemPageQuery) {
		long start = System.currentTimeMillis();
		PageItemResult result = null;
		try {
			Request request = Request.Post("https://thor.weidian.com/ares/search.new/1.0").addHeader("method", "POST").addHeader("scheme", "https").addHeader("path", "/ares/search.new/1.0")
					.addHeader("authority", "thor.weidian.com")

					.addHeader("userid", "336429028").addHeader("accept-language", "zh-cn").addHeader("accept-encoding", "br, gzip, deflate")
					.addHeader("content-type", "application/x-www-form-urlencoded").addHeader("x-origin", "wechat.weidian.com")
					.addHeader("referer", "https://servicewechat.com/wx4b74228baa15489a/169/page-frame.html").addHeader("token", token).userAgent(AGENT);
			List<NameValuePair> pairList = Lists.newArrayList();
			pairList.add(new BasicNameValuePair("param", JSON.toJSONString(itemPageQuery)));
			pairList.add(new BasicNameValuePair("context", content));
			request.bodyForm(pairList, Charset.forName("UTF-8"));
			Response response = request.execute();
			String asString = response.returnContent().asString(Charset.forName("UTF-8"));
			result = JSON.parseObject(asString, PageItemResult.class);
			return result.getResult().getViewDatas();
		} catch (Exception e) {
			LOGGER.error("queryPageItemList_error params:{}", itemPageQuery, e);
		} finally {
			LOGGER.error("queryPageItemList_info params:{},cost:{},result:{}", JSON.toJSONString(itemPageQuery), (System.currentTimeMillis() - start), JSON.toJSONString(result));
		}
		return Lists.newArrayList();
	}

	/**
	 * 根据关键字查询列表
	 * <p>
	 * 商品链接：https://weidian.com/?userid=1024903213
	 *
	 * @return
	 */
	public List<Result.ResultBean.ShopsBean> queryShopList() {
		long start = System.currentTimeMillis();
		try {
			Request request = Request.Post("https://thor.weidian.com/ares/search.searchShop/1.0").addHeader("method", "POST").addHeader("scheme", "https")
					.addHeader("path", "/ares/search.searchShop/1.0").addHeader("authority", "thor.weidian.com")

					.addHeader("userid", "336429028").addHeader("accept-language", "zh-cn").addHeader("accept-encoding", "br, gzip, deflate")
					.addHeader("content-type", "application/x-www-form-urlencoded").addHeader("x-origin", "wechat.weidian.com")
					.addHeader("referer", "https://servicewechat.com/wx4b74228baa15489a/169/page-frame.html").addHeader("token", token).userAgent(AGENT);
			List<NameValuePair> pairList = Lists.newArrayList();
			pairList.add(new BasicNameValuePair("param", "{\"keyword\":\"\\u96f6\\u98df\",\"limit\":20,\"page\":1,\"source\":\"smart_search\",\"businessId\":216}"));
			pairList.add(new BasicNameValuePair("context", content));
			request.bodyForm(pairList, Charset.forName("UTF-8"));
			Response response = request.execute();
			String asString = response.returnContent().asString(Charset.forName("UTF-8"));
			Result result = JSON.parseObject(asString, Result.class);
			return result.getResult().getShops();
		} catch (Exception e) {
			LOGGER.error("queryShopList_error params:{}", 1, e);
		} finally {
			LOGGER.info("queryShopList_info params:{},cost:{}", 1, (System.currentTimeMillis() - start));
		}
		return Lists.newArrayList();
	}

	/**
	 * 根据商品ID查询详情
	 * <p>
	 * 商品链接：https://weidian.com/item.html?itemID=2655537246
	 *
	 * @return
	 */
	public ItemResult.ResultBean.ItemInfoBean queryItemDetail(String itemId) {
		long start = System.currentTimeMillis();
		try {
			Request request = Request.Post("https://vap.gw.weidian.com/wxbuyer/ares/item.getItemDetail/1.5").addHeader("method", "POST").addHeader("scheme", "/wxbuyer/ares/item.getItemDetail/1.5")
					.addHeader("path", "vap.gw.weidian.com").addHeader("authority", "https")

					.addHeader("accept-language", "zh-cn").addHeader("accept-encoding", "br, gzip, deflate").addHeader("content-type", "application/x-www-form-urlencoded")
					.addHeader("x-origin", "wechat.weidian.com").addHeader("referer", "https://servicewechat.com/wx4b74228baa15489a/169/page-frame.html").addHeader("token", token).userAgent(AGENT);
			List<NameValuePair> pairList = Lists.newArrayList();
			pairList.add(new BasicNameValuePair("request", "{\"itemId\":" + Long.valueOf(itemId) + "}"));
			pairList.add(new BasicNameValuePair("context", content));
			request.bodyForm(pairList, Charset.forName("UTF-8"));
			Response response = request.execute();
			String asString = response.returnContent().asString(Charset.forName("UTF-8"));
			ItemResult result = JSON.parseObject(asString, ItemResult.class);
			return result.getResult().getItemInfo();
		} catch (Exception e) {
			LOGGER.error("queryItemDetail_error params:{}", itemId, e);
		} finally {
			LOGGER.error("queryItemDetail_info itemId:{},cost:{}", itemId, (System.currentTimeMillis() - start));
		}
		return null;
	}

}
